package com.monolithiot.sso.common.util;

import com.monolithiot.sso.common.context.Constants;

import java.util.regex.Pattern;

/**
 * 2018/12/13 Create by 郭文梁
 * ReturnUrlUtil
 * 返回地址工具类
 *
 * @author 郭文梁
 * @date 2018/12/13
 */
public class ReturnUrlUtil {
    private static final Pattern URL_WITH_PARAMS_PATTERN = Pattern.compile("^.*\\?.*$");
    private static final String WITH_PARAMS_URL_TEMPLATE = "%s&%s=%s";
    private static final String WITHOUT_PARAMS_URL_TEMPLATE = "%s?%s=%s";

    /**
     * 在ReturnUrl后拼接Token参数
     *
     * @param urlStr 返回地址
     * @param token  Token
     * @return returnUrl +(with) token
     */
    public static String appendToken(String urlStr, String token) {
        if (URL_WITH_PARAMS_PATTERN.matcher(urlStr).find()) {
            return String.format(WITH_PARAMS_URL_TEMPLATE, urlStr, Constants.Auth.DEFAULT_RETURN_TOKEN_PARAM_NAME, token);
        } else {
            return String.format(WITHOUT_PARAMS_URL_TEMPLATE, urlStr, Constants.Auth.DEFAULT_RETURN_TOKEN_PARAM_NAME, token);
        }
    }

}
